import utils from './utils.js' // 公共方法
import RequestManager from './requestManager.js'; // 请求管理器
import common from '@/config/common.js';
export const BASE_URL = common.API_BASE_URL; //测试域名
const manager = new RequestManager()

const baseRequest = async (url, method, data = {}, loading = true) => {
	let requestId = manager.generateId(method, url, data)
	// if (!requestId) {
	// 	utils.showToast("操作频繁")
	// 	return false
	// }
	const header = {}
	header.Authorization = uni.getStorageSync('token') || '';
	return new Promise((resolve, reject) => {
		// 开启loading
		loading && uni.showLoading({
			mask: true,
			title: '正在加载',
		});
		uni.request({
			url: BASE_URL + url,
			method: method || 'GET',
			header: header,
			timeout: 10000,
			data: data || {},
			complete: () => {
				manager.deleteById(requestId)
				// uni.$emit('hideLoading');
				uni.hideLoading();
			},
			success: (successData) => {
				const res = successData.data;
				if (successData.statusCode == 200) {
					switch (res.code) {
						case 200:
							resolve(res)
							break;
						case 401:
							uni.removeStorageSync('userInfo');
							uni.removeStorageSync('token');
							utils.showToast('登录已过期！')
							uni.$emit('showLogin');
							const timer = setTimeout(() => {
								uni.switchTab({
									url: '/pages/mine/mine',
									success: () => {
										clearTimeout(timer)
									}
								})
							}, 500)
							reject(res)
							break;
						case 500:
							utils.showToast(res.msg || '系统错误')
							reject(res)
							break;
						default:
							utils.showToast(res.msg || '系统错误')
							reject(res)
							break;
					}
				} else {
					utils.showToast(successData.errMsg || '系统错误')
					reject(successData)
				}
			},
			fail: (err) => {
				utils.showToast(err.errMsg || '系统错误')
				reject(err)
			}
		})
	})
	// let loadingPromise = loading ? new Promise((resolve) => {
	// 	uni.$emit('showLoading');
	// 	resolve()
	// }) : Promise.resolve()

	// return Promise.all([
	// 	loadingPromise,

	// ]).finally(() => {
	// 	uni.$emit('hideLoading');
	// });
}


const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})



export default request